package com.zhixin.fans.ks.ui.login;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ActivityUtils;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.tencent.mmkv.MMKV;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zhixin.fans.ks.KeyConstant;
import com.zhixin.fans.ks.R;
import com.zhixin.fans.ks.api.CommonApi;
import com.zhixin.fans.ks.api.res.UserInfoRes;
import com.zhixin.fans.ks.api.res.UserToken;
import com.zhixin.fans.ks.manager.UserInfoManager;
import com.zhixin.fans.ks.ui.base.BaseDaggerActivity;
import com.zhixin.fans.ks.ui.dialog.AuthListener;
import com.zhixin.fans.ks.ui.main.MainActivity;
import com.zhixin.fans.ks.ui.utils.LogUtil;

import org.eenie.common.subscribes.ProgressSubscriber;
import org.eenie.common.views.QMUIWindowInsetLinearLayout;
import org.eenie.common.views.TopBarLayout;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class LoginActivity extends BaseDaggerActivity {
    public static final String ROUTE_PATH = "/main/login";

    @BindView(R.id.fragment_container)
    QMUIWindowInsetLinearLayout mFragmentContainer;
    @BindView(R.id.btn_login)
    QMUIRoundButton mBtnLogin;
    @BindView(R.id.lay_login_board)
    FrameLayout mLayLoginBoard;
    @BindView(R.id.btn_qq_login)
    ImageView mBtnQqLogin;
    @BindView(R.id.btn_wx_login)
    ImageView mBtnWxLogin;

//    CoupleApi mCoupleApi;


    CommonApi mCommonApi;

    UserInfoManager mUserInfoManager;
    @BindView(R.id.top_bar)
    TopBarLayout mTopBar;


    @Override
    public int initContentView() {
        return R.layout.activity_login;
    }

    @Override
    public void initInjector() {
        mCommonApi = getApplicationComponent().getApiManager().create(CommonApi.class);
        mUserInfoManager = getCoupleAppComponent().getUserInfoManager();
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);

        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }


    @OnClick(R.id.btn_login)
    public void login() {
        UMShareAPI.get(mContext).deleteOauth(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                System.out.println("onStart");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                System.out.println("onComplete");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                System.out.println("onError");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                System.out.println("onCancel");
            }
        });


//        MMKV.defaultMMKV().putString(KeyConstant.KEY_TOKEN, "token");
//        countDown(3)
//                .subscribe(new ProgressSubscriber<Long>(mContext, "正在拼命登录...") {
//                    @Override
//                    public void onNext(Long aLong) {
//
//                    }
//
//                    @Override
//                    public void onFinish() {
//                        ARouter.getInstance().build(OrderListActivity.ROUTE_PATH).navigation();
//                        finish();
//                    }
//                });


    }


    private Observable<Long> countDown(long time) {
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(time + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return time - aLong;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }


    @OnClick(R.id.btn_qq_login)
    public void loginByQQ() {
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(mContext).setShareConfig(config);
        UMShareAPI.get(mContext).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, new AuthListener(mContext) {
            @Override
            public void onSuccess(SHARE_MEDIA share_media, int code, Map<String, String> map) {
                LogUtil.e(JSON.toJSONString(map));
                loginThirdQQ(map.get("openid"), map.get("profile_image_url"), map.get("name"));
            }
        });
    }

    @OnClick(R.id.btn_wx_login)
    public void loginByWx() {


        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);


        UMShareAPI umShareAPI = UMShareAPI.get(mContext);
        umShareAPI.setShareConfig(config);
        umShareAPI.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, new AuthListener(mContext) {
            @Override
            public void onSuccess(SHARE_MEDIA share_media, int code, Map<String, String> map) {
                LogUtil.e(JSON.toJSONString(map));
                loginThirdWx(map.get("openid"), map.get("profile_image_url"), map.get("name"), map.get("unionid"));
            }
        });


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(mContext).onActivityResult(requestCode, resultCode, data);
    }


    private void loginThirdWx(String openId, String img_url, String nickName, String unionid) {
        mCommonApi.loginByWx(openId, img_url, nickName, unionid)
                .flatMap(new Function<UserToken, ObservableSource<UserInfoRes>>() {
                    @Override
                    public ObservableSource<UserInfoRes> apply(UserToken userInfo) throws Exception {
                        MMKV.defaultMMKV().putString(KeyConstant.KEY_TOKEN, userInfo.getToken());
                        return mCommonApi.fetchUserInfo(userInfo.getToken());
                    }
                })
                .subscribe(new ProgressSubscriber<UserInfoRes>() {
                    @Override
                    public void onNext(UserInfoRes userInfoDetail) {
                        mUserInfoManager.save(userInfoDetail.getUserInfo());
                        ActivityUtils.finishAllActivities();
                        startActivity(new Intent(mContext, MainActivity.class));
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

    private void loginThirdQQ(String openId, String img_url, String nickName) {
        mCommonApi.loginByQQ(openId, img_url, nickName)
                .flatMap(new Function<UserToken, ObservableSource<UserInfoRes>>() {
                    @Override
                    public ObservableSource<UserInfoRes> apply(UserToken userInfo) throws Exception {
                        MMKV.defaultMMKV().putString(KeyConstant.KEY_TOKEN, userInfo.getToken());
                        return mCommonApi.fetchUserInfo(userInfo.getToken());
                    }
                })
                .subscribe(new ProgressSubscriber<UserInfoRes>() {
                    @Override
                    public void onNext(UserInfoRes userInfoDetail) {
                        mUserInfoManager.save(userInfoDetail.getUserInfo());
                        ActivityUtils.finishAllActivities();
                        startActivity(new Intent(mContext, MainActivity.class));
                    }

                    @Override
                    public void onFinish() {

                    }
                });

    }


}
